<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Shop;
use App\Models\ShopModel;
use App\Models\ShopTypeModel;
use App\Models\StoreModel;
use App\Providers\OrderShipped;
use App\Sevrice\Elasticsearch;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Qiniu\Auth;
use App\Admin\Actions\Post\Restore;
use App\Admin\Actions\Modal\memberModal;
class ShopController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Shop(), function (Grid $grid) {
            $grid->column('shop_id')->sortable();
            $grid->column('shop_nick');
            $grid->column('shop_price');
            $grid->column('shop_logo')->explode(',')->image('', '50', '50');
            $grid->column('shop_repertory');
            $grid->column('shop_sales');
            $grid->column('shop_tid');
            $grid->column('shop_status')->using([1 => '上架', 0 => '下架', 3 => '已售空']);
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (request('_scope_') == 'trashed') {
                    $actions->append(new Restore(ShopModel::class));
                }
            });
            $grid->filter(function (Grid\Filter $filter) {
                // 更改为 panel 布局
                $filter->panel();
                $filter->scope('trashed', '回收站')->onlyTrashed();
                $filter->equal('shop_id');
                $filter->like('shop_nick');
                $filter->equal('shop_type')->select(['id' => 1, 'text' => '电脑']);
            });
            $grid->export();
            $grid->tools(function  (Grid\Tools  $tools)  {
                //Excel导入
                $tools->append(new  memberModal());
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Shop(), function (Show $show) {
            $show->field('shop_id');
            $show->field('shop_nick');
            $show->field('shop_desc')->unescape();
            $show->field('shop_price');
            $show->field('shop_logo')->explode(',')->image();
            $show->field('shop_repertory');
            $show->field('shop_sales');
            $show->field('shop_tid');
            $show->field('shop_status');

            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Shop(), function (Form $form) {
            $form->display('shop_id');
            $form->text('shop_nick')->rules(['required'], ['required' => '商品标题必填']);
            $form->text('shop_price')->rules(['required'], ['required' => '请输入商品价格']);
            $form->multipleImage('shop_logo')->rules(['required'], ['required' => '商品图片不能为空'])->disk('qiniu')->uniqueName()->saveFullUrl()->maxSize(1024 * 50)->saving(function ($query) {
                if (is_array($query)) {
                    return implode(',', $query);
                }
                return $query;
            });
            $form->text('shop_repertory')->rules(['required'], ['required' => '请输入商品库存']);
            $form->text('shop_sales')->rules(['required'], ['required' => '商品销量']);
            $form->select('shop_tid')->options('shopType');
            $form->select('shop_name', '店铺')->options('storeInfo');
            $form->radio('shop_status', '商品状态')->options([
                1 => '上架',
                2 => '下架'
            ])->saving(function ($query) {
                if ($query == '上架') {
                    return $query = 1;
                }
                return $query = 0;
            });
            $form->editor('shop_desc')->disk('qiniu');
            $form->display('created_at');
            $form->display('updated_at');
            $form->saved(function (Form $form, $result) {
                // 判断是否是新增操作
                if ($form->isCreating()) {
                    // 自增ID
                    $newId = $result;
                    event(new OrderShipped($newId));
                    if (!$newId) {
                        return $form->error('数据保存失败');
                    }
                    return;
                }
            });
        });
    }

    /**
     * @return array
     * 查询商品分类信息
     */
    function shopType()
    {
        $type = ShopTypeModel::get()->toArray();
        foreach ($type as $k => $v) {
            $type[$k]['id'] = $v['tid'];
            $type[$k]['text'] = $v['type_name'];
        }
        return $type;
    }

    function storeInfo()
    {
        $type = StoreModel::get()->toArray();
        foreach ($type as $k => $v) {
            $type[$k]['id'] = $v['store_id'];
            $type[$k]['text'] = $v['store_name'];
        }
        return $type;
    }

    /**
     * @param int $id
     * @return bool|\Illuminate\Http\Response|mixed|\Symfony\Component\HttpFoundation\Response
     * 批量删除的七牛云图片后删除对应数据
     */
    function destroy($id)
    {
        $id = $id . ',';
        $ids = explode(',', $id);
        $logo = ShopModel::whereIn('shop_id', $ids)->pluck('shop_logo')->toArray();
        $dataLogo = [];
        foreach ($logo as $k => $v) {
            $logo[$k] = explode(',', $v);
            foreach ($logo[$k] as $val) {
                $str = substr($val, strlen('http://rg8wu28pg.hn-bkt.clouddn.com/'));
                array_push($dataLogo, $str);
            }
        }
        $accessKey = 'Zq-edBxpHMDVqGZuLgFWO3uYNYBskpvkITh39Id2';
        $secretKey = 'DeZlwCzaWiaUuNLIQptfi4g--xoH-L_9_xpS17y0';
        $bucket = 'liang2001a';
        $auth = new Auth($accessKey, $secretKey);
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        //每次最多不能超过1000个
        $keys = $dataLogo;
        $ops = $bucketManager->buildBatchDelete($bucket, $keys);
        list($ret, $err) = $bucketManager->batch($ops);
        if ($err) {
            return false;
        } else {
            return $this->form()->destroy($id);
        }
    }


}
